# -*- coding: utf-8 -*-
import json


def obj_to_json_bytes(data: object):
    json_str = json.dumps(data)
    return bytes(json_str, encoding="utf8")


def set_to_data(data: bytes, cmd: int):
    redata = b''
    redata += bytes([0x57, 0x72, cmd, 0x01])
    redata += (len(data)).to_bytes(length=2, byteorder="big")
    redata += data
    check_sum = 0
    for x in redata:
        check_sum += x
    redata += bytes([check_sum & 0xFF])
    return redata


def print_cmd_hex(text: str, data: bytes, cmd: int):
    a_bytes = set_to_data(data, cmd)
    aa_data = ' '.join(['%02X' % b for b in a_bytes])
    print("\033[1;34m%-10s\033[0m : \033[1;33m%10s\033[0m" % (text, aa_data))


print_cmd_hex("寻找设备", b'', 0x01)

print_cmd_hex("获取网络状态", b'', 0x02)

print_cmd_hex("修改 wifi 信息",
              obj_to_json_bytes({
                  "ssid": "junlan",
                  "ps": "junlan2013",
                  "auth": 3
              }),
              0x03)

print_cmd_hex("修改 url 信息",
              obj_to_json_bytes({
                  "url": "http://192.168.1.25:8098/image",
              }),
              0x04)

print_cmd_hex("抓拍",
              bytes([
                  0x01, 0x01, 0x01, 0x01, 0x01, 0x01,  # 设备标识符
                  0x01, 0x01, 0x01, 0x01,  # 事件时间戳
              ]),
              0x05)

print_cmd_hex("OTA",
              obj_to_json_bytes({
                  "url": "https://api.demoks.com/ota/cat_eye.bin",
              }),
              0x06)

print_cmd_hex("摄像机参数设置",
              bytes([
                  0x01,  # OV2640的自动曝光水平设置
                  # set level (0 ~ 4)

                  0x00,  # 白平衡设置
                  # 0: auto
                  # 1: sunny
                  # 2: cloudy
                  # 3: office
                  # 4: home

                  0x02,  # 色度集
                  # 0: -2
                  # 1: -1
                  # 2:  0
                  # 3: +1
                  # 4: +2

                  0x04,  # 亮度设置
                  # 0: (0X00)-2
                  # 1: (0X10)-1
                  # 2: (0X20) 0
                  # 3: (0X30)+1
                  # 4: (0X40)+2

                  0x04,  # 对比度设置
                  # 0: -2
                  # 1: -1
                  # 2:  0
                  # 3: +1
                  # 4: +2

                  0x00,  # 特效设置
                  # 0: Normal mode
                  # 1: negative
                  # 2: Black and white
                  # 3: red
                  # 4: green
                  # 5: blue
                  # 6: Restoring ancient ways

                  0x00,  # 条状试验
                  # 0:  禁用
                  # 1： 启用（注意：OV2640的色条叠加在图像上）

                  0x01,  # mode
                  # 0: Initialize (800*600)
                  # 1: Initialize (1600*1200)
              ]),
              0x07)

print_cmd_hex("二维码识别", b'', 0x77)
